package com.czl.module_service.viewmodel.assetUse

import android.util.Log
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.AddApplySortBean
import com.czl.base.data.bean.tengyun.SortBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_service.adapter.asset.BorrowSortChoosedAdapter

class BorrowApplyAddViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var currentPage = 1
    val uc = UiChangeEvent()
    var sortBean : SortBean? = null
    var companyName = ObservableField(model.getLocalUserInfo()?.companyName)
    var returnBackTime = ObservableField("")
    var note = ObservableField("")
    var list : MutableList<SortBean> = arrayListOf()
    var adapter : BorrowSortChoosedAdapter? = null
    var businessType = 1

    val onReturnTimeClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.onReturnTimeEvent.call()
    })

    val onBorrowCompanyClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.onBorrowCompanyEvent.call()
    })

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<MutableList<SortBean>> = SingleLiveEvent()
        val roleCompleteEvent: SingleLiveEvent<List<Any?>> = SingleLiveEvent()
        val onReturnTimeEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val onBorrowCompanyEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val clearFacilityListEvent: SingleLiveEvent<Int> = SingleLiveEvent()
    }

    val addSortLayout: BindingCommand<Any> = BindingCommand(BindingAction {
        getSortList()
    })

    val addUsageSort : BindingCommand<Any> = BindingCommand(BindingAction {
        addUseApplication()
    })

    fun getSortList() {
        val list : MutableList<SortBean> = arrayListOf()
        list.add(SortBean())
        uc.loadCompleteEvent.postValue(list)
    }

    fun getRoleProcessList() {
        model.mTengYunHttpDataSource.getRoleProcessList(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "businessId" to 1
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<List<Any?>>>() {
                override fun onResult(t: BaseBean<List<Any?>>) {
                    if (t.state == 0) {
                        uc.roleCompleteEvent.postValue(t.data)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    // 新增领用申请
    private fun addUseApplication() {
        val data = adapter?.data
        list = adapter?.data!!
        Log.e("viewModel", "data:" +data?.size)
        val filterList = list.filter { it. sortId != null }
        if (returnBackTime.get().isNullOrEmpty()) {
            showNormalToast("请选择归还时间")
            return
        }
        if (note.get().isNullOrEmpty()) {
            showNormalToast("请填写借用原因")
            return
        }
        if (filterList.isEmpty()) {
            showNormalToast("请选择物品")
            return
        }
        val filterList2 = filterList.filter { it.sortNum == 0 }
        if (filterList2.isNotEmpty()) {
            showNormalToast("物品数量不能为0")
            return
        }
        val list : MutableList<AddApplySortBean> = arrayListOf()
        filterList.forEach {
            val bean = AddApplySortBean()
            bean.id = it.sortId
            bean.name = it.sortName
            bean.count = it.sortNum
            bean.type = 2
            bean.sortModel = it.sortModel
            bean.applyNum = it.sortNum
            bean.price = it.price
            bean.otherValue = it
            bean.otherValue?.count = it.sortNum!!
            list.add(bean)
        }
        model.mTengYunHttpDataSource.addUseApplication(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "borrowCompanyId" to model.getLoginCompanyId()?.toInt(),
                    "planSendBacktime" to returnBackTime.get(),
                    "note" to note.get(),
                    "workId" to "1",
                    "list" to list,
                    "applicationType" to 1,
                    "businesstype" to businessType
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("新增成功")
                        uc.clearFacilityListEvent.postValue(0)
                        LiveBusCenter.postGoToTabEvent(1)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

}